package qeug.shsh.opplugin;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.BeforeClickEvent;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.apache.commons.net.util.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.EventObject;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.opplugin
 * @className: AddPaymentInfoServicePlugin
 * @author: wenyx
 * @description: TODO
 * @date: 2024/11/20 13:46
 * @version: 1.0
 */
public class AddPaymentInfoServicePlugin extends AbstractFormPlugin {

    private String idcard = "";
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        try {
            getHRUser("");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        try {
            if(name.equals("payer")){
                Object payer = this.getModel().getValue("payer");
                if(payer!=null){
                    DynamicObject payerInfo = (DynamicObject) payer;
                    JSONObject param = new JSONObject();
                    param.put("NUMBER",payerInfo.getString("number"));
                    String hrUser = getHRUser(param.toString());
                    JSONObject hrUserInfo = JSONObject.parseObject(hrUser);
                    JSONObject personinfo = hrUserInfo.getJSONArray("PERSONINFO").getJSONObject(0);
                    OperateOption option = OperateOption.create();
                    option.setVariableValue("idcard", personinfo.getString("IDCARD"));
                    idcard = personinfo.getString("IDCARD");
                    if(personinfo.getJSONArray("BANKS")!=null){
                        JSONObject banks = personinfo.getJSONArray("BANKS").getJSONObject(0);
                        String payeraccount = banks.getString("PAYERACCOUNT");//银行账号
                        String payeraccountname = banks.getString("PAYERACCOUNTNAME");//收款人
                        String payerbank = banks.getString("PAYERBANK"); //开户银行
//                        DynamicObject bebank = BusinessDataServiceHelper.loadSingle(payerbank,"bd_bebank", "number");
                        DynamicObject bebank = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("number", "=", payerbank).toArray());
                        if(bebank!=null){
                            this.getModel().setValue("payeraccount",payeraccount);
                            this.getModel().setValue("payeraccountname",payeraccountname);
                            this.getModel().setValue("payerbank",bebank) ;
                        }else {
                            this.getView().showErrorNotification("费控系统未找到该银行！");
                        }
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("operatepanel");
        this.addClickListeners("btnsave");
    }

    @Override
    public void beforeClick(BeforeClickEvent evt) {
        super.beforeClick(evt);
        Control source = (Control) evt.getSource();
        if (StringUtils.equals("btnsave", source.getKey())) {
            Object payer = this.getModel().getValue("payer");
            if (payer != null) {
                DynamicObject payerInfo = (DynamicObject) payer;
                ORM orm = ORM.create();
                DynamicObject supplier = orm.newDynamicObject("bd_supplier");
//                DynamicObject supUser = BusinessDataServiceHelper.loadSingle("bos_user", "id", new QFilter("number", "=", number).toArray());
                DynamicObject supp = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("employee.id", "=", payerInfo.get("id")).toArray());
                if (supp != null) {
                    supplier = supp;
                }
                supplier.set("number", payerInfo.getString("number"));//编码
                supplier.set("name", payerInfo.getString("name"));//名称cc
//            supplier.set("bizpartner_phone", phone);//电话
                JSONObject param = new JSONObject();
                param.put("NUMBER",payerInfo.getString("number"));
                String hrUser = null;
                try {
                    hrUser = getHRUser(param.toString());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                JSONObject hrUserInfo = JSONObject.parseObject(hrUser);
                JSONObject personinfo = hrUserInfo.getJSONArray("PERSONINFO").getJSONObject(0);
                supplier.set("idno", personinfo.getString("IDCARD"));//身份证
                supplier.set("type", "4");//伙伴类型
                supplier.set("ctrlstrategy", "2");//控制策略“默认自由分配”
                DynamicObject createOrgName = BusinessDataServiceHelper.loadSingle("bos_adminorg", new QFilter("name", "=", "盛虹集团").toArray());
                supplier.set("createorg", createOrgName);//创建组织默认盛虹石化
//                DynamicObject supPer = BusinessDataServiceHelper.loadSingle("bos_user", new QFilter("number", "=", number).toArray());
                supplier.set("employee", payerInfo);//员工
                supplier.set("enable", "1");
                supplier.set("status", "C");
                DynamicObjectCollection banksCollection = supplier.getDynamicObjectCollection("entry_bank");//银行分录
                DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("number", "=", "CNY").toArray());
                DynamicObjectType supBankType = banksCollection.getDynamicObjectType();
                banksCollection.clear();
                DynamicObject banksEntry = new DynamicObject(supBankType);
                //同一个银行账号 不能同时存在在不同编码的客商内
                String payerAccount = this.getModel().getValue("payeraccount").toString();//银行账号
                String payerAccountName = this.getModel().getValue("payeraccountname").toString();//账户名称
//                            String payerBank = bank.getString("payerbank");//开户行号
                DynamicObject payerBankNum = (DynamicObject)this.getModel().getValue("payerbank");//开户银行编码
//                    DynamicObject bankName = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("number", "=", payerBankNum).toArray());
                banksEntry.set("bankaccount", payerAccount);//银行账号
                banksEntry.set("accountname", payerAccountName);//账户名称
                banksEntry.set("currency", currencyNumber);//币种代码
                banksEntry.set("bank", payerBankNum);//开户银行
                boolean isdefault = true;
                banksEntry.set("isdefault_bank", isdefault);//默认是否职员
                banksCollection.add(banksEntry);
                DynamicObjectCollection entry_groupstandard = supplier.getDynamicObjectCollection("entry_groupstandard");//供应商分类
                DynamicObjectType groupstandardType = entry_groupstandard.getDynamicObjectType();
                DynamicObject groupstandardEntry = new DynamicObject(groupstandardType);
                DynamicObject bd_suppliergroupstandard = BusinessDataServiceHelper.loadSingle("bd_suppliergroupstandard", new QFilter("number", "=", "JBFLBZ").toArray());
                groupstandardEntry.set("standardid", bd_suppliergroupstandard);//分类标准
                DynamicObject bd_suppliergroup = BusinessDataServiceHelper.loadSingle("bd_suppliergroup", new QFilter("number", "=", "SK98").toArray());
                groupstandardEntry.set("groupid", bd_suppliergroup);//分类
                entry_groupstandard.add(groupstandardEntry);
                OperationResult bd_supplier = SaveServiceHelper.saveOperate("bd_supplier", new DynamicObject[]{supplier}, OperateOption.create());//新增修改
                if (bd_supplier.isSuccess()) {
                    System.out.println("人员供应商新增修改成功");
                    } else {
                    System.out.println("人员供应商新增修改失败，错误代码：" + bd_supplier);
                    }
            }
            evt.setCancel(true);  // 取消后续处理，将不会再触发click事件
        }
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        if(evt.getItemKey().equals("btnsave")) {
            Object payer = this.getModel().getValue("payer");
            if (payer != null) {
                DynamicObject payerInfo = (DynamicObject) payer;
                ORM orm = ORM.create();
                DynamicObject supplier = orm.newDynamicObject("bd_supplier");
//                DynamicObject supUser = BusinessDataServiceHelper.loadSingle("bos_user", "id", new QFilter("number", "=", number).toArray());
                DynamicObject supp = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("employee.id", "=", payerInfo.get("id")).toArray());
                if (supp != null) {
                    supplier = supp;
                }
                supplier.set("number", payerInfo.getString("number"));//编码
                supplier.set("name", payerInfo.getString("name"));//名称
//            supplier.set("bizpartner_phone", phone);//电话
                supplier.set("idno", payerInfo.getString("idno"));//身份证
                supplier.set("type", "4");//伙伴类型
                supplier.set("ctrlstrategy", "2");//控制策略“默认自由分配”
                DynamicObject createOrgName = BusinessDataServiceHelper.loadSingle("bos_adminorg", new QFilter("name", "=", "盛虹集团").toArray());
                supplier.set("createorg", createOrgName);//创建组织默认盛虹石化
//                DynamicObject supPer = BusinessDataServiceHelper.loadSingle("bos_user", new QFilter("number", "=", number).toArray());
                supplier.set("employee", payerInfo);//员工
                supplier.set("enable", "1");
                supplier.set("status", "C");
                DynamicObjectCollection banksCollection = supplier.getDynamicObjectCollection("entry_bank");//银行分录
                DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("number", "=", "CNY").toArray());
                DynamicObjectType supBankType = banksCollection.getDynamicObjectType();
                banksCollection.clear();
                    DynamicObject banksEntry = new DynamicObject(supBankType);
                    //同一个银行账号 不能同时存在在不同编码的客商内
                    String payerAccount = this.getModel().getValue("payeraccount").toString();//银行账号
                    String payerAccountName = this.getModel().getValue("payeraccountname").toString();//账户名称
//                            String payerBank = bank.getString("payerbank");//开户行号
                DynamicObject payerBankNum = (DynamicObject)this.getModel().getValue("payerbank");//开户银行编码
//                    DynamicObject bankName = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("number", "=", payerBankNum).toArray());
                    banksEntry.set("bankaccount", payerAccount);//银行账号
                    banksEntry.set("accountname", payerAccountName);//账户名称
                    banksEntry.set("currency", currencyNumber);//币种代码
                    banksEntry.set("bank", payerBankNum);//开户银行
                    boolean isdefault = true;
                    banksEntry.set("isdefault_bank", isdefault);//默认是否职员
                    banksCollection.add(banksEntry);
            }
        }
    }

    /**
     *
     * @param
     * @throws Exception
     */
    public String getHRUser(String param) throws Exception {
//        String basicAuthUserName = System.getProperty("hr.user");
//        String basicAuthPassword = System.getProperty("hr.password");
//        String hrUrl = System.getProperty("hr.url");
        String basicAuthUserName = "ccsuser";
        String basicAuthPassword = "ccs2sappoqas";
        String basic = basicAuthUserName + ":" + basicAuthPassword;
        String encde = Base64Utils.encodeToString(basic.getBytes(StandardCharsets.UTF_8));
        String hrUrl = "http://shpoqas.shenghongpec.com:50000/RESTAdapter/CCS2HR/PersonSyn";
        String json = HttpRequest.post(hrUrl)
                .header("Authorization", "Basic " + encde)
                .body(param)
                .execute().body();
        return json;
    }


    private String getHeader() {
        String auth = "ccsuser:ccs2sappoqas";
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }
}
